package org.fatewa.engine.exception;

import org.fatewa.engine.advice.protocol.RayquazaResponse;
import org.fatewa.engine.design.advice.AbstractExceptionProcessor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据库唯一约束冲突异常处理器
 *
 * @author fatewa
 */
public class DuplicateKeyProcessor extends AbstractExceptionProcessor<DuplicateKeyException> {
    private static final Pattern DUPLICATE_KEY_REGEXP = Pattern.compile("\\((.*?)\\)=\\((.*?)\\)");

    @Override
    public RayquazaResponse map(DuplicateKeyException e) {
        RayquazaResponse response = new RayquazaResponse();
        // 现在创建 matcher 对象
        Matcher m = DUPLICATE_KEY_REGEXP.matcher(Objects.requireNonNull(e.getMessage()));
        if (m.find()) {
            String left = m.group(1);
            String right = m.group(2);
            response.msg(String.format("字段 <%s> 不可重复,  %s = %s 已存在", left, left, right));
        }
        return response
                .code(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
